package com.dx.financehy.config.wx.ma;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaRedisConfigImpl;
import cn.hutool.core.collection.CollectionUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <pre>
 * @描述：
 * @作者：CLD
 * @创建时间：2022-05-26 15:57
 * </pre>
 **/
@Slf4j
@AllArgsConstructor
@Configuration
@EnableConfigurationProperties(WxMaProperties.class)
public class WxMaConfiguration {

    private final WxMaProperties properties;

    @Bean
    public WxMaService wxMaService() {
        final List<WxMaProperties.MaConfig> configs = this.properties.getConfigs();
        if (CollectionUtil.isEmpty(configs)) {
            throw new RuntimeException("未添加小程序相关配置，请核实！");
        }
        WxMaService service = new WxMaServiceImpl();
        WxMaProperties.RedisConfig redisConfig = this.properties.getRedisConfig();
        service.setMultiConfigs(configs
                .stream().map(a -> {
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    JedisPool jedisPool = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
                            redisConfig.getTimeout(), redisConfig.getPassword(),redisConfig.getDatabase());
                    WxMaRedisConfigImpl config = new WxMaRedisConfigImpl(jedisPool);
                    config.setAppid(a.getAppid());
                    config.setSecret(a.getSecret());
                    config.setToken(a.getToken());
                    config.setAesKey(a.getAesKey());
                    config.setMsgDataFormat(a.getMsgDataFormat());
                    config.setRedisKeyPrefix(redisConfig.getKeyPrefix());
                    return config;
                }).collect(Collectors.toMap(WxMaDefaultConfigImpl::getAppid, a -> a, (o, n) -> o)));
        return service;
    }

}
